//引入axios
import axios, { type AxiosRequestHeaders, type AxiosResponse } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
/* 定义response对象的data接口 */
interface ResponseData<T> {
  code: number;
  data: T;
  value: string;
}

const request = axios.create({
  baseURL: "/app-apis",
  timeout: 5000,
});

request.interceptors.request.use((config) => {
  if (config.method === "get") {
    config.params.access_token = "c494ae44-3adc-48ca-8749-5128a53358d7";
  }
  if (config.method === "post") {
    config.params.access_token = "c494ae44-3adc-48ca-8749-5128a53358d7";
  }
  return config;
});

request.interceptors.response.use(
  /* 约束一下response */
  async (response: AxiosResponse<ResponseData<any>>) => {
    // 对响应数据做点什么
    const res = response.data;
    if (res.code !== 20000 && res.code !== 200) {
      /* 成功数据的code值为20000/200 */
      // 统一的错误提示
      ElMessage({
        message:
          (typeof res.data == "string" && res.data) || res.value || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(res.value);
    } else {
      return res.data; /* 返回成功响应数据中的data属性数据 */
    }
  },
  (error) => {
    // 对响应错误做点什么
    if (error.message.indexOf("timeout") != -1) {
      ElMessage.error("网络超时");
    } else if (error.message == "Network Error") {
      ElMessage.error("网络连接错误");
    } else {
      if (error.response.data) ElMessage.error(error.response.statusText);
      else ElMessage.error("接口路径找不到");
    }
    return Promise.reject(error);
  }
);
export default request;
